/**
 * userlog控制器
 *
 * @author sxf
 * @email sxf02615@163.com
 * @date 2025/1/15
 */
package com.sxf.crm.controller;


import com.sxf.crm.entity.UserLog;
import com.sxf.crm.entity.User;
import com.sxf.crm.repository.UserLogRepository;
import com.sxf.crm.repository.UserRepository;
import com.sxf.crm.security.JwtTokenUtil;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import jakarta.servlet.http.HttpServletRequest;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.access.prepost.PreAuthorize;
import lombok.RequiredArgsConstructor;

@RestController
@RequestMapping("/api/logs")
@RequiredArgsConstructor
public class UserLogController {
    private static final Logger logger = LoggerFactory.getLogger(UserLogController.class);
    
    private final UserLogRepository userLogRepository;
    private final UserRepository userRepository;
    private final JwtTokenUtil jwtTokenUtil;

    @PreAuthorize("hasAuthority('userlog:view') or principal.isAdmin")
    @GetMapping
    public ResponseEntity<Page<UserLogDTO>> getLogs(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size,
            @RequestParam(required = false) String username,
            @RequestParam(required = false) String action,
            @RequestParam(required = false) String startDate,
            @RequestParam(required = false) String endDate) {
        try {
            // 解析日期参数
            Long startTime = null;
            Long endTime = null;
            
            if (startDate != null && !startDate.trim().isEmpty()) {
                try {
                    // 假设日期格式为 YYYY-MM-DD，转换为当天开始时间戳
                    java.time.LocalDate start = java.time.LocalDate.parse(startDate);
                    startTime = start.atStartOfDay(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli();
                } catch (Exception e) {
                    logger.warn("Invalid start date format: {}", startDate);
                }
            }
            
            if (endDate != null && !endDate.trim().isEmpty()) {
                try {
                    // 假设日期格式为 YYYY-MM-DD，转换为当天结束时间戳
                    java.time.LocalDate end = java.time.LocalDate.parse(endDate);
                    endTime = end.atTime(23, 59, 59, 999999999).atZone(java.time.ZoneId.systemDefault()).toInstant().toEpochMilli();
                } catch (Exception e) {
                    logger.warn("Invalid end date format: {}", endDate);
                }
            }
            
            Page<UserLogDTO> logs = userLogRepository.findByConditions(
                    username, action, startTime, endTime, PageRequest.of(page, size))
                    .map(UserLogDTO::fromLog);
            return ResponseEntity.ok(logs);
        } catch (Exception e) {
            logger.error("Error fetching logs", e);
            return ResponseEntity.internalServerError().build();
        }
    }

    @PostMapping
    public ResponseEntity<UserLogDTO> createLog(@RequestBody UserLogDTO logDTO, HttpServletRequest request) {
        try {
            String token = request.getHeader("Authorization");
            if (token == null || !token.startsWith("Bearer ")) {
                logger.warn("Invalid or missing token in request");
                return ResponseEntity.badRequest().body(null);
            }

            token = token.substring(7);
            String username = jwtTokenUtil.getUsernameFromToken(token);
            if (username == null) {
                logger.warn("Could not extract username from token");
                return ResponseEntity.badRequest().body(null);
            }

            java.util.Optional<User> userOpt = userRepository.findByUsername(username);
            if (userOpt.isPresent()) {
                try {
                    User user = userOpt.get();
                    UserLog log = new UserLog();
                    log.setUser(user);
                    log.setAction(logDTO.action);
                    log.setDescription(logDTO.description);
                    log.setIpAddress(request.getRemoteAddr());
                    log.setCreateAt(System.currentTimeMillis());
                    UserLog saved = userLogRepository.save(log);
                    return ResponseEntity.ok(UserLogDTO.fromLog(saved));
                } catch (Exception e) {
                    logger.error("Error saving log", e);
                    return ResponseEntity.status(500).body(null);
                }
            } else {
                logger.warn("User not found: {}", username);
                return ResponseEntity.badRequest().body(null);
            }
        } catch (Exception e) {
            logger.error("Error creating log", e);
            return ResponseEntity.status(500).body(null);
        }
    }

    public static class UserLogDTO {
        public Long id;
        public String username;
        public String action;
        public String description;
        public String ipAddress;
        public String createAt;

        public static UserLogDTO fromLog(UserLog log) {
            UserLogDTO dto = new UserLogDTO();
            dto.id = log.getId();
            dto.username = log.getUser() != null ? log.getUser().getUsername() : null;
            dto.action = log.getAction();
            dto.description = log.getDescription();
            dto.ipAddress = log.getIpAddress();
            // 将时间戳转换为可读的日期时间字符串
            if (log.getCreateAt() != null) {
                java.time.Instant instant = java.time.Instant.ofEpochMilli(log.getCreateAt());
                java.time.LocalDateTime dateTime = java.time.LocalDateTime.ofInstant(instant, java.time.ZoneId.systemDefault());
                dto.createAt = dateTime.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            }
            return dto;
        }
    }
} 